package com.hxkj.service.wechat.impl;

import com.hxkj.client.service.AppletArticleServiceClient;
import com.hxkj.domain.enums.ArticleExceptionEnum;
import com.hxkj.domain.enums.SiteExceptionEnum;
import com.hxkj.domain.po.AppletArticle;
import com.hxkj.domain.po.AuthUser;
import com.hxkj.service.wechat.AppletArticleService;
import com.hxkj.token.utils.TokenUtils;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName AppletArticleServiceImpl
 * @Author zzx
 * @Date 2018/6/12 15:21
 * @Version 1.0
 */
@Service
@Slf4j
public class AppletArticleServiceImpl implements AppletArticleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppletArticleServiceImpl.class);

    @Autowired
    private AppletArticleServiceClient appletArticleServiceClient;


    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public ResultPageStruct<AppletArticle> getAppletArticleList(AppletArticle article, PageTo pageParam) throws Exception {
        if (pageParam.getPageNum() == null || pageParam.getPageSize() == null) {
            pageParam.setPageNum(1);
            pageParam.setPageSize(10);
        }
        ResultPageStruct<AppletArticle> result = new ResultPageStruct<>();
        ParameterDataStruct<AppletArticle> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(article);
        parameterDataStruct.setPageTo(pageParam);

        if (article.getDelTag() == null) {
            throw new CustomException(ArticleExceptionEnum.AUTHROLE_DELAG_NULL);
        }
        if (article.getCreateTimeStart() == null && article.getCreateTimeEnd() != null) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_CREATETIMESTRAT_NULL);
        }
        if (article.getCreateTimeStart() != null && article.getCreateTimeEnd() == null) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_CREATETIMESEND_NULL);
        }
        //将前端传过来的文章创建结束时间 + 一天减一秒
        if(article.getCreateTimeEnd()!=null){
            article.setCreateTimeEnd(article.getCreateTimeEnd() + 24 * 60 * 60 * 1000 - 1);
        }

        try {
            //查询文章列表（包含文章回收站列表）
            result = appletArticleServiceClient.getAppletArticleList(parameterDataStruct);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取文章列表失败:{}", e.getMessage());

        }
        result.setCode(null);
        result.setMessage(null);
        return result;
    }


    @Override
    public AppletArticle getAppletArticle(AppletArticle article) throws Exception {
        ResultDataStruct<AppletArticle> result = new ResultDataStruct();
        if (article.getArticleId() == null) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_ID_NULL);
        }
        try {
            // 查询一篇文章
            result = appletArticleServiceClient.getAppletArticle(article);
            if (result.getCode() != null) {
                throw new CustomException(ArticleExceptionEnum.getEnumByCode(result.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询文章失败:{}", e);
            throw e;
        }
        return result.getData();
    }

    @Override
    public void updateAppletArticle(AppletArticle article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        if (article.getArticleId() == null) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_ID_NULL);
        }
        //字段校验
        verifyData(article);
        AuthUser authUser = (AuthUser) tokenUtils.getTokenUserInfo();
        //如果作者为空 取登录的用户名
        if (StringUtils.isBlank(article.getAuthor())) {
            article.setAuthor(authUser.getUserName());
        }
        article.setAgentId(authUser.getUserId());
        article.setUpdateTime(System.currentTimeMillis());
        try {
            //修改文章
            result = appletArticleServiceClient.updateAppletArticle(article);
            if (result.getCode() != null) {
                throw new CustomException(ArticleExceptionEnum.getEnumByCode(result.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void AppletArticleRecover(AppletArticle article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        if (StringUtils.isBlank(article.getArticleIds())) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_ID_NULL);
        }
        try {
            //文章恢复
            result = appletArticleServiceClient.AppletArticleRecover(article);
            if (result.getCode() != null) {
                throw new CustomException(ArticleExceptionEnum.getEnumByCode(result.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void removerAppletArticle(AppletArticle article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        if (StringUtils.isBlank(article.getArticleIds())) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_ID_NULL);
        }
        try {
            // 移除文章至回收站
            result = appletArticleServiceClient.removerAppletArticle(article);
            if (result.getCode() != null) {
                throw new CustomException(SiteExceptionEnum.getEnumByCode(result.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void saveAppletArticle(AppletArticle article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        //字段校验
        verifyData(article);
        AuthUser authUser = (AuthUser) tokenUtils.getTokenUserInfo();
        //如果作者为空 取登录的用户名
        if (StringUtils.isBlank(article.getAuthor())) {
            article.setAuthor(authUser.getUserName());
        }
        article.setAgentId(authUser.getUserId());
        //设置发布时间
        article.setCreateTime(System.currentTimeMillis());
        try {
            //新增文章
            result = appletArticleServiceClient.saveAppletArticle(article);
            if (result.getCode() != null) {
                throw new CustomException(ArticleExceptionEnum.getEnumByCode(result.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void deleteAppletArticle(AppletArticle article) throws Exception {
        ResultMessageStruct result = new ResultMessageStruct();
        if (StringUtils.isBlank(article.getArticleIds())) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_ID_NULL);
        }
        try {
            // 回收站彻底删除文章
            result = appletArticleServiceClient.deleteAppletArticle(article);
            if (result.getCode() != null) {
                throw new CustomException(SiteExceptionEnum.getEnumByCode(result.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * 新增 和 编辑 时 对文章的参数进行校验
     * @param article
     * @throws CustomException
     */
    private void verifyData(AppletArticle article) throws CustomException {
        String imgUrls [] = {};
        if(StringUtils.isNotBlank(article.getImgUrl())){
            imgUrls = article.getImgUrl().split(",");
        }
        if (article.getTitle() == null) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_HEADLINE_NULL);
        }
        if (article.getClassifyId() == null) {
            throw new CustomException(ArticleExceptionEnum.AUTHROLE_COLUMNID_NULL);
        }
        if (article.getDetail() == null) {
            throw new CustomException(ArticleExceptionEnum.AUTHROLE_PARTICULARS_NULL);
        }
        if(article.getDetail().length()>20000){
            throw new CustomException(ArticleExceptionEnum.ARTICLE_DETAIL_NUMBER_ERROR);
        }
        if (article.getCoverNumber() == null) {
            throw new CustomException(ArticleExceptionEnum.ARTICLE_COVER_NUMBER_NULL);
        }
        if (article.getCoverNumber() == 1) {
            if(imgUrls.length!=1){
                throw new CustomException(ArticleExceptionEnum.ARTICLE_IMG_NUMBER1_ERRO);
            }
        }
        if (article.getCoverNumber() == 2) {
            if(imgUrls.length!=3){
                throw new CustomException(ArticleExceptionEnum.ARTICLE_IMG_NUMBER3_ERRO);
            }
        }
    }

}

